//
//  CZCarController.m
//  TCProject
//
//  Created by admin on 16/1/29.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "CZCarController.h"
#import "CZCar.h"
#import "CZCarCell.h"
#import "AccountManager.h"
#import "CZCarInfoController.h"

@interface CZCarController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UIBarButtonItem *rightButton;
@property (nonatomic, strong) BMPage *page;
@property (nonatomic, strong) NSMutableArray *cars;

- (IBAction)addCarAction:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *addCarButton;


@end

@implementation CZCarController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 280.f;
    
    self.cars = [NSMutableArray array];
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData:)];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = [BMPage defaultPage];
        [self getData:YES];
    }];

}

- (void)getData:(BOOL)refresh
{
    NSMutableDictionary *params = [self.page nextPage];
    if (!params) {
        [self.tableView.footer noticeNoMoreData];
        return;
    }
    
    params[@"ownerId"] = @([AccountManager sharedInstance].user.ID);
    BMRequest *request = [BMRequest requestWithPath:@"getMyTrucks.htm" contentKey:@"trucks"];
    request.params = params;
    [CZCar postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        if ([self.tableView.header isRefreshing]) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer resetNoMoreData];
        }
        if ([self.tableView.footer isRefreshing]) {
            [self.tableView.footer endRefreshing];
        }
        if (response.status == kResultOK) {
            if (refresh) {
                [self.cars removeAllObjects];
            }
            _page = response.page;
            [self.cars addObjectsFromArray:response.result];
            [self.tableView reloadData];
        } else {
            if (error) {
                [self showHint:@"未知错误"];
            } else {
                [self showHint:response.msg];
            }
        }
    }];
}

- (UIBarButtonItem *)rightButton
{
    if (!_rightButton) {
        _rightButton = [[UIBarButtonItem alloc] initWithTitle:@"添加车辆" style:UIBarButtonItemStylePlain target:self action:@selector(addCarAction:)];
        [_rightButton setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.f], NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal];
    }
    return _rightButton;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView.header beginRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger count = _cars.count;
    if (count) {
        self.addCarButton.hidden = YES;
        self.tableView.hidden = NO;
        self.navigationItem.rightBarButtonItem = self.rightButton;
    } else {
        self.addCarButton.hidden = NO;
        self.tableView.hidden = YES;
        self.navigationItem.rightBarButtonItem = nil;
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    weakSelf(self);
    CZCarCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.car = _cars[indexPath.row];
    [cell setOperation:^(NSUInteger tag) {
        if (tag) {  //删除操作
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否删除该车辆?" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addAction:cancleAction];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                [weakSelf deleteTask:_cars[indexPath.row]];
            }];
            [alertVC addAction:okAction];
            //            [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
            //            [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
            [weakSelf presentViewController:alertVC animated:YES completion:nil];
        } else {    //编辑信息
            CZCarInfoController *infoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"carInfo"];
            infoVC.car = _cars[indexPath.row];
            [weakSelf showViewController:infoVC sender:nil];
        }
    }];
    return cell;
}

/**
 *  删除车辆
 */
- (void)deleteTask:(CZCar *)car
{
    BMRequest *request = [BMRequest requestWithPath:@"delete.htm"];
    request.params = @{@"id": @(car.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            [self.cars removeObject:car];
            [self.tableView reloadData];
        } else {
            [self showHint:@"删除车辆失败"];
        }
    }];
}



- (IBAction)addCarAction:(id)sender {
    CZCarInfoController *infoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"carInfo"];
    [self showViewController:infoVC sender:nil];

}
@end
